package org.pettyfox.pfpay.biz;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.pettyfox.pfpay.entity.PayAlone;
import org.pettyfox.pfpay.pojo.ListPage;
import org.pettyfox.pfpay.utils.ClazzUtil;
import org.pettyfox.pfpay.utils.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

public class BaseBiz<T extends Mapper<E>,E>  {
    @Autowired
    T mapper;
    public E get(Object id){
        return mapper.selectByPrimaryKey(id);
    }
    public Object listPage(ListPage listPage) {
        String order = listPage.getOrder();
        Map<String,Object> result = new HashMap<>();
        PageHelper.startPage(Optional.ofNullable(listPage.getPageNum()).orElse(1),
                Optional.ofNullable(listPage.getPageSize()).orElse(20));
        Example query = new Example(PayAlone.class);
        Example.Criteria criteria = query.createCriteria();
        //排序
        if(!StringUtils.isEmpty(order) && ClazzUtil.isField(PayAlone.class,order)){
            order = Tool.humpToLine(order);//驼峰转sql字段

            if(ListPage.OrderDirection.ASC.equals(listPage.getDirection())){
                query.setOrderByClause(order+" ASC");
            }else if(ListPage.OrderDirection.DESC.equals(listPage.getDirection())){
                query.setOrderByClause(order+" DESC");
            }

        }
        //筛选
        if(!StringUtils.isEmpty(listPage.getFilters())){
            String[] filters = listPage.getFilters().split("///");
            for(String filter : filters){
                String[] kv = filter.split("//");
                if(kv != null && kv.length == 2){
                    criteria.andIn(kv[0], Arrays.asList(kv[1].split("/")));
                }
            }
        }

        List<E> list = mapper.selectByExample(query);

        PageInfo<E> pageInfo = new PageInfo<>(list);

        result.put("data",pageInfo);
        result.put("status",200);
        return result;
    }
    public Object createRow( E payAlone){
        Map<String,Object> map = new HashMap<>();
        mapper.insertSelective(payAlone);
        map.put("data","");
        map.put("status",200);
        return map;
    }

    public Object updateRow( E payAlone) {
        Map<String,Object> map = new HashMap<>();
        mapper.updateByPrimaryKeySelective(payAlone);
        map.put("data","");
        map.put("status",200);
        return map;
    }

    public Object deleteRow( String id) {
        Map<String,Object> map = new HashMap<>();
        mapper.deleteByPrimaryKey(id);
        map.put("data","");
        map.put("status",200);
        return map;
    }
}
